package com.itheima.socketWork05;
import java.io.*;
import java.net.Socket;
import java.util.UUID;
public class ServerThread implements Runnable{
    private Socket socket;
    public ServerThread(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            // 根据socket对象获取输入流，读取客户端发送的数据
            BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
            // 为防止文件名称重复，采用32位UUID作为文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 创建输出流指向当前模块目录，保存文件
            BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("day12_socket\\" + uuid + ".jpg"));
            // 读写操作
            int len;
            byte[] bys = new byte[1024];
            while ((len = input.read(bys)) != -1) {
                output.write(bys, 0, len);
            }
            // 读取完文件数据，把socket输入流禁用
            socket.shutdownInput();
            // 关闭操作当前文件的流
            output.close();

            // 根据socket对象获取输出流，给客户端反馈
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
            writer.println("上传成功");
            // 释放socket资源
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
